<?php

namespace app\admin\controller\org;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use think\Db;

/**
 * 组织结构类别
 *
 * @icon fa fa-circle-o
 */
class Orgpay extends Backend
{
    
    /**
     * Orgpay模型对象
     * @var \app\admin\model\org\Orgpay
     */
    protected $model = null;
    protected $searchFields = 'name|linkman';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\org\Orgpay;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index(){
        //当前是否为关联查询
        $this->relationSearch = false;
        if($this->request->isAjax()){
            if($this->request->request('keyField')){
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where('type', 2)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('type', 2)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key => $row) {
                $row->sort =  ($key+1+$offset);
            }
            $list = collection($list)->toArray();
            $result = array('total'=>$total, 'rows'=>$list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if (!$params['mobile'] || !\think\Validate::regex($params['mobile'], "^1\d{10}$")) {
                    $this->error(__('手机号不正确'));
                }
                if($params['type'] == 2){//付费单位
                    if(empty($params['start_time']) || empty($params['end_time'])){
                        $this->error(__('付费单位需要有起始日期！'));
                    }
                    $params['start_time'] = strtotime($params['start_time'] );
                    $params['end_time'] = strtotime($params['end_time'] );
                    if($params['start_time'] >=$params['end_time'] ){
                        $this->error(__('结束时间必须大于开始时间！'));
                    }
                }
                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看课程
     */
    public function course()
    {
        $org_cate_id = $this->request->param('ids');
        $this->view->assign("ids", $org_cate_id);
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->model = new \app\admin\model\learn\Course;
        $this->searchFields = 'course.id,course.name';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['orgpay','teacher','admin'])
                ->where('orgpay.org_cate_id', $org_cate_id)
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['orgpay','teacher','admin'])
                ->where('orgpay.org_cate_id', $org_cate_id)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>$row) {
                $row->sort = ($key+1+$offset);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 添加课程列表
     */
    public function courseadd()
    {
        $ids = $this->request->param('ids');
        $this->view->assign("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->model = new \app\admin\model\learn\Course;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $courseids = Db::name('learn_course_orgpay')->where('org_cate_id', $ids)->column('course_id');
            $where2 = true;
            if($courseids){
                $where2 = 'course.id not in ('.implode(',', $courseids).')';
            }
            $total = $this->model
                ->with(['orgpay','teacher','admin'])
                ->where($where)
                ->where($where2)
                ->where('course.org_cate_id', '=', 0)
//                ->where('orgpay.org_cate_id <> '.$ids.' OR orgpay.org_cate_id IS NULL')
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['orgpay','teacher','admin'])
                ->where('course.org_cate_id', '=', 0)
//                ->where('orgpay.org_cate_id <> '.$ids.' OR orgpay.org_cate_id IS NULL')
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>$row) {
                $row->sort = ($key+1+$offset);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /*
     * 绑定单次课程
     */
    public function bindcourse($ids)
    {
        $this->model = new \app\admin\model\org\Orgpaycourse;
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                if(isset($params['ids']) && !empty($params['ids'])){
                    $ids = explode(',', $params['ids']);
                    $data = Db::name('learn_course')->field('origin_price,price,id')->where('id', 'in', $ids)->select();
                    $price_arr = array();
                    foreach($data as $val){
                        $price_arr[$val['id']] = $val;
                    }
                    $data = [];
                    foreach ($ids as $key=>$val){
                        $data[$key]['org_cate_id'] = $params['task_id'];
                        $data[$key]['course_id'] = $val;
                        $data[$key]['origin_price'] = isset($price_arr[$val]['origin_price'])?$price_arr[$val]['origin_price']:'0.00';
                        $data[$key]['price'] = isset($price_arr[$val]['price'])?$price_arr[$val]['price']:'0.00';
                        $data[$key]['createtime'] = time();
                    }
                    $result = $this->model->saveAll($data);
                    if ($result === false) {
                        $this->error($this->model->getError());
                    }
                    $this->success();
                }
                $this->error('课程编号错误！');
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /*
     * 删除绑定单次课程
     * @param null $ids
     */
    public function coursedel($ids = null)
    {
        $this->model = new \app\admin\model\org\Orgpaycourse;
        $params = $this->request->post();
        if (isset($params['ids']) && !empty($params['ids'])) {
            $res = $this->model->where('course_id', 'in', $params['ids'])->where('org_cate_id', '=', $params['org_id'])->delete();
            if($res===false){
                $this->error($this->model->getError());
            }
            $this->success();
        }
        $this->error('编号错误！');
    }

}
